import { use as useEcharts } from "echarts/core";
import { CanvasRenderer } from "echarts/renderers";
import { LineChart } from "echarts/charts";
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from "echarts/components";
import { getChartsOptions } from "@utils";
import { TxProps } from "./prop";

export function use(props: TxProps) {
  const chartOptions = computed(() => {
    const list = props.data as LisZksjItem[]
    if (list && list.length) {
      var sj = 1, old = ''
      const legend = new Map<string, { it: LisZksjItem, data: { [k: string]: number } }>()
        , xAxis = ['', ...new Set(list.map(it => {
          const id = it.zkpid, data = legend.get(id) || { it, data: {} }
            , jlsj = it.jlsj.substring(5, 10).replace(/[\/-]/g, '')
            , sjid = jlsj + (old === jlsj ? ((sj = 1)) : sj++)
          data.data[sjid] = it.cs1
          legend.set(id, data)
          return sjid
        })), '']
        , legendArr = [...legend.values()]
        , { kssj, jssj, zbmc, zkgzdldm, yqmc } = props.param
      return getChartsOptions(
        `仪器名称：${yqmc}控项目：${zbmc} 日期区间：${kssj} - ${jssj}\n质控规则：${zkgzdldm || ''} `,
        xAxis,
        yAxis,
        legendArr.map(({ it, data }) => {
          return {
            name: `----批号：${it.ph || ""}【质控品】名称：${it.mc || ""} 效期：${it.yxq || ""} 供应商：${it.gys || ""} `,
            data: xAxis.map(key => key && data[key] ? yAxis[(data[key])] || '' : 'NAN'),
            type: 'line'
          }
        })
      )
    } else
      return undefined
  }),
    chartCom = ref(),
    yAxis = ['', '+2', '+3', 'normal', '+4', '+-', '+1', '']
  useEcharts([
    CanvasRenderer,
    GridComponent,
    LineChart,
    TitleComponent,
    TooltipComponent,
    LegendComponent,
  ])
  return { chartOptions, chartCom }
}